import { Injectable, NotFoundException } from "@nestjs/common";
import { File } from "@/modules/file/entities/file.entity";
import { InjectRepository } from "@nestjs/typeorm";
import { Brackets, Repository } from "typeorm";
import { MinioService } from "@/modules/file/minio/minio.service";
import { MD5 } from 'crypto-js';

@Injectable()
export class FileService {
  constructor(
    @InjectRepository(File)
    private fileRepository: Repository<File>,
    private minioService: MinioService,
  ) {
  }

  // 创建
  async createInformation(File: File): Promise<File> {
    return this.fileRepository.save(File);
  }

  async uploadFile(req: any, file: any, body: any): Promise<File> {
    await this.minioService.uploadFile('joyvalleyoss', file.originalname, file.buffer);
    const uploadfile = new File();
    uploadfile.notes = body.notes;
    uploadfile.filePaths = file.originalname;
    uploadfile.userId =req.user.userId;
    uploadfile.username = req.user.username;

    const timestamp = Date.now().toString();
    const uniqueCode = timestamp.slice(-4);
    // 使用加密编号
    uploadfile.code = MD5(uniqueCode).toString();
    return this.createInformation(uploadfile);
  }

  async findOneInformationByCode(code: string): Promise<File | null> {
    const result = await this.fileRepository.findOne({ where: { code: code } });

    if (!result) {
      throw new NotFoundException(`没有找到该code:${code}的信息`);
    }

    return result;
  }

  // 分页查询
  async findWithPagination(
    pageNo: number,
    pageSize: number,
    username: string,
  ): Promise<File[]> {
    const queryBuilder = this.fileRepository.createQueryBuilder('file');

    queryBuilder.skip((pageNo - 1) * pageSize).take(pageSize);

    if (username) {
      queryBuilder.andWhere(
        new Brackets((qb) => {
          qb.where('file.username LIKE :username', { username: `%${username}%` });
        }),
      );
    }
    return queryBuilder.getMany();
  }

  //更新
  async updateFile(id: number, file: File): Promise<File> {
    const result = await this.fileRepository.findOne({ where: { id: id } });

    if (!result) {
      throw new NotFoundException(`没有找到该id:${id}的信息`);
    }

    return this.fileRepository.save({ ...file, id: id });
  }

  //软删除
  async softDeleteFile(id: number): Promise<void> {
    await this.fileRepository.softDelete(id);
  }

  //删除
  async removeFile(id: number): Promise<void> {
    await this.fileRepository.delete(id);
  }
}